const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//将Uint8Array转换为str
function uint8ArrayToStr(uint8Arrys) {
  //数组与中文之间的转换---start
  // var testStr = str2arrayBuffer('中文转换测试dvadsgaag550！#')
  // var strUint8Array = new Uint8Array(testStr)
  var strArrayBuffer = arrayToBuffer(uint8Arrys)//将Uint8Array转换为ArrayBuffer
  var strUint16Array = new Uint16Array(strArrayBuffer)//将ArrayBuffer转换为Uint16Array
  var testStrNew = array2Str(strUint16Array)//将Uint16Array转换为汉字
  return testStrNew.replace(/(^\s+)|(\s+$)/g, "");
}

function array2Str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}
// function str2arrayBuffer(str) {
//   var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
//   var bufView = new Uint16Array(buf);
//   for (var i = 0, strLen = str.length; i < strLen; i++) {
//     bufView[i] = str.charCodeAt(i);
//   }
//   return buf;
// }

function arrayToBuffer(array) {
  var buffer = new ArrayBuffer(array.length)
  var dataView8 = new Uint8Array(buffer)
  for (var i = 0; i < array.length; i++) {
    dataView8[i] = array[i]
  }
  return buffer
}

function stringToArrayBuffer(hexString){
  var typedArray3 = new Uint8Array(hexString.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))
  var buffer3 = typedArray3.buffer
  return buffer3
}
//数组与中文之间的转换---stop
//性别转换
function getSexFromCode(strSexCode)
{
  if ('0' == strSexCode.charAt(0)) {
    return "未知";
  }
  else if ('1' == strSexCode.charAt(0)) {
    return "男";
  }
  else if ('2' == strSexCode.charAt(0)) {
    return "女";
  }
  else if ('9' == strSexCode.charAt(0)) {
    return "未说明";
  }
  return "未定义";
}
//民族转换
function getNationFromCode(strNationCode)
{
  if (strNationCode == ("01")) {
    return "汉";
  }
  else if (strNationCode == ("02")) {
    return "蒙古";
  }
  else if (strNationCode == ("03")) {
    return "回";
  }
  else if (strNationCode == ("04")) {
    return "藏";
  }
  else if (strNationCode == ("05")) {
    return "维吾尔";
  }
  else if (strNationCode == ("06")) {
    return "苗";
  }
  else if (strNationCode == ("07")) {
    return "彝";
  }
  else if (strNationCode == ("08")) {
    return "壮";
  }
  else if (strNationCode == ("09")) {
    return "布依";
  }
  else if (strNationCode == ("10")) {
    return "朝鲜";
  }
  else if (strNationCode == ("11")) {
    return "满";
  }
  else if (strNationCode == ("12")) {
    return "侗";
  }
  else if (strNationCode == ("13")) {
    return "瑶";
  }
  else if (strNationCode == ("14")) {
    return "白";
  }
  else if (strNationCode == ("15")) {
    return "土家";
  }
  else if (strNationCode == ("16")) {
    return "哈尼";
  }
  else if (strNationCode == ("17")) {
    return "哈萨克";
  }
  else if (strNationCode == ("18")) {
    return "傣";
  }
  else if (strNationCode == ("19")) {
    return "黎";
  }
  else if (strNationCode == ("20")) {
    return "傈僳";
  }
  else if (strNationCode == ("21")) {
    return "佤";
  }
  else if (strNationCode == ("22")) {
    return "畲";
  }
  else if (strNationCode == ("23")) {
    return "高山";
  }
  else if (strNationCode == ("24")) {
    return "拉祜";
  }
  else if (strNationCode == ("25")) {
    return "水";
  }
  else if (strNationCode == ("26")) {
    return "东乡";
  }
  else if (strNationCode == ("27")) {
    return "纳西";
  }
  else if (strNationCode == ("28")) {
    return "景颇";
  }
  else if (strNationCode == ("29")) {
    return "柯尔克孜";
  }
  else if (strNationCode == ("30")) {
    return "土";
  }
  else if (strNationCode == ("31")) {
    return "达斡尔";
  }
  else if (strNationCode == ("32")) {
    return "仫佬";
  }
  else if (strNationCode == ("33")) {
    return "羌";
  }
  else if (strNationCode == ("34")) {
    return "布朗";
  }
  else if (strNationCode == ("35")) {
    return "撒拉";
  }
  else if (strNationCode == ("36")) {
    return "毛南";
  }
  else if (strNationCode == ("37")) {
    return "仡佬";
  }
  else if (strNationCode == ("38")) {
    return "锡伯";
  }
  else if (strNationCode == ("39")) {
    return "阿昌";
  }
  else if (strNationCode == ("40")) {
    return "普米";
  }
  else if (strNationCode == ("41")) {
    return "塔吉克";
  }
  else if (strNationCode == ("42")) {
    return "怒";
  }
  else if (strNationCode == ("43")) {
    return "乌孜别克";
  }
  else if (strNationCode == ("44")) {
    return "俄罗斯";
  }
  else if (strNationCode == ("45")) {
    return "鄂温克";
  }
  else if (strNationCode == ("46")) {
    return "德昂";
  }
  else if (strNationCode == ("47")) {
    return "保安";
  }
  else if (strNationCode == ("48")) {
    return "裕固";
  }
  else if (strNationCode == ("49")) {
    return "京";
  }
  else if (strNationCode == ("50")) {
    return "塔塔尔";
  }
  else if (strNationCode == ("51")) {
    return "独龙";
  }
  else if (strNationCode == ("52")) {
    return "鄂伦春";
  }
  else if (strNationCode == ("53")) {
    return "赫哲";
  }
  else if (strNationCode == ("54")) {
    return "门巴";
  }
  else if (strNationCode == ("55")) {
    return "珞巴";
  }
  else if (strNationCode == ("56")) {
    return "基诺";
  }
  else if (strNationCode == ("97")) {
    return "其他";
  }
  else if (strNationCode == ("98")) {
    return "外国血统中国籍人士";
  }

  return "未知";
}



//读卡结果分析
function readCardIsOk(_i_bys_resp) {

  var strName = '';
  var strSex = '';
  var strNation = '';
  var strBirth = null;
  var strAddr = null;
  var strIdCode = null;
  var strIssue = null;
  var strBeginDate = null;
  var strEndDate = null;

	var SW1 = _i_bys_resp[7];
	var SW2 = _i_bys_resp[8];
	var SW3 = _i_bys_resp[9];

	if ((0x0 != SW1) || (0x0 != SW2) || ((0x90) != SW3)) {
		return false;
	}

	if (_i_bys_resp.length < 1024) {
		return false;
	}

	///////////////////////////////////////////////////
	//
	var i = 0;
	var j = 0;
	var iOffset = 0;

	var bysName = new Array(30);
	var bysSexCode = new Array(2);
	var bysNationCode = new Array(4);
	var bysBirth = new Array(16);
	var bysAddr = new Array(70);
	var bysIdCode = new Array(36);
	var bysIssue = new Array(30);
	var bysBeginDate = new Array(16);
	var bysEndDate = new Array(16);

	var iTextSize = 0;
	var iPhotoSize = 0;
	var iFingerSize = 0;

	iTextSize = _i_bys_resp[10] << 8 + _i_bys_resp[11];
	iPhotoSize = _i_bys_resp[12] << 8 + _i_bys_resp[13];
	iFingerSize = _i_bys_resp[14] << 8 + _i_bys_resp[15];

	///////////////////////////////////////////////////
	//截取数据

	//iOffset = 16;
	iOffset = 14;

	//截取姓名
	j = 0;
	for (i = iOffset; i < (iOffset + 30); i++) {
		bysName[j] = _i_bys_resp[i];
		j++;
	}
	try {
		strName = uint8ArrayToStr(bysName)
	} catch (Exception) {}
	iOffset += 30;

	//截取性别
	j = 0;
	for (i = iOffset; i < (iOffset + 2); i++) {
		bysSexCode[j] = _i_bys_resp[i];
		j++;
	}
	var strSexCode = null;
	try {
		strSexCode = uint8ArrayToStr(bysSexCode);
		strSex = getSexFromCode(strSexCode);
	} catch (Exception) {}
	iOffset += 2;

	//截取民族
	j = 0;
	for (i = iOffset; i < (iOffset + 4); i++) {
		bysNationCode[j] = _i_bys_resp[i];
		j++;
	}
	var strNationCode = null;
	try {
		strNationCode = uint8ArrayToStr(bysNationCode, );
		strNation = getNationFromCode(strNationCode);
	} catch (Exception) {}
	iOffset += 4;

	//截取生日
	j = 0;
	for (i = iOffset; i < (iOffset + 16); i++) {
		bysBirth[j] = _i_bys_resp[i];
		j++;
	}
	try {
		strBirth = new String(bysBirth, "UTF-16LE");
	} catch (Exception) {}
	iOffset += 16;

	//截取地址
	j = 0;
	for (i = iOffset; i < (iOffset + 70); i++) {
		bysAddr[j] = _i_bys_resp[i];
		j++;
	}
	try {
		strAddr = uint8ArrayToStr(bysAddr);
	} catch (Exception) {}
	iOffset += 70;

	//截取身份证号
	j = 0;
	for (i = iOffset; i < (iOffset + 36); i++) {
		bysIdCode[j] = _i_bys_resp[i];
		j++;
	}
	try {
		strIdCode = uint8ArrayToStr(bysIdCode);		
	} catch (Exception) {}
	iOffset += 36;

	//截取签发机关
	j = 0;
	for (i = iOffset; i < (iOffset + 30); i++) {
		bysIssue[j] = _i_bys_resp[i];
		j++;
	}
	try {
		strIssue = uint8ArrayToStr(bysIssue);
	} catch (Exception) {}
	iOffset += 30;

	//截取有效期开始日期
	j = 0;
	for (i = iOffset; i < (iOffset + 16); i++) {
		bysBeginDate[j] = _i_bys_resp[i];
		j++;
	}
	try {
		strBeginDate = uint8ArrayToStr(bysBeginDate);
	} catch (Exception) {}
	iOffset += 16;

	//截取有效期结束日期
	j = 0;
	for (i = iOffset; i < (iOffset + 16); i++) {
		bysEndDate[j] = _i_bys_resp[i];
		j++;
	}
	try {
		if (bysEndDate[0] >= '0' && bysEndDate[0] <= '9') {
			// strEndDate = new String(bysEndDate, "UTF-16LE");
		} else {
			// strEndDate = new String(bysEndDate, "UTF-16LE");
		}
		strEndDate = uint8ArrayToStr(bysEndDate)
	} catch (Exception) {}
	iOffset += 16;

	// //照片
	// var wlt = new byte[1024];
	// byte[] bmp = new byte[14 + 40 + 308 * 126];
	// for (i = 0; i < iPhotoSize; i++) {
	//   wlt[i] = _i_bys_resp[16 + iTextSize + i];
	// }
	// //int iResult = JniCall.hxgc_Wlt2Bmp(wlt, bmp, 0);
	// int iResult = DecodeWlt.hxgc_Wlt2Bmp(wlt, bmp, 708);
	// Bitmap bitmapIdPhoto = null;
	// if (iResult != -1) {
	//   bitmapIdPhoto = BitmapFactory.decodeByteArray(bmp, 0, bmp.length);
	// }


  return {
    strName,
    strSex,
    strNation,
    strBirth,
    strAddr,
    strIdCode,
    strIssue,
    strBeginDate,
    strEndDate
  };

}

//寻卡结果分析
const searchCardIsOk = (result) => {
	var SW1 = result[7];
	var SW2 = result[8];
	var SW3 = result[9];
	if ((0x0 != SW1) || (0x0 != SW2) || (0x9F) != SW3) {
		return false;
	}
	return true;
}

//选卡结果分析
const selectCardIsOk = (result) => {
	var SW1 = result[7];
	var SW2 = result[8];
	var SW3 = result[9];
	if ((0x0 != SW1) || (0x0 != SW2) || (0x90) != SW3) {
		return false;
	}
	return true;
}

const error = msg => {
  wx.showToast({
    icon:'error',
    title: msg,
  })
  throw msg
}

const replaceErrorMsg = ({errCode,errMsg}) => {
  let codeMsg = errMsg;
  if(errCode == -1){
    codeMsg = '已连接';
  }else if(errCode == 10001){
    codeMsg = '请检查手机是否已打开蓝牙';
  }else if(errCode == 10000){
    codeMsg = '未初始化蓝牙适配器';
  }else if(errCode == 10002){
    codeMsg = '没有找到指定设备';
  }else if(errCode == 10003){
    codeMsg = '连接失败';
  }else if(errCode == 10006){
    codeMsg = '当前连接已断开';
  }else if(errCode == 10012){
    codeMsg = '连接超时';
  }
  return codeMsg
}	

const catchError = e => {
  wx.hideLoading({
    success: (res) => {},
  })
  wx.showModal({
    title:'提示',
    content:replaceErrorMsg(e),
    cancelColor: 'cancelColor',
  })
}



module.exports = {
  formatTime: formatTime,
  uint8ArrayToStr: uint8ArrayToStr,
  stringToArrayBuffer: stringToArrayBuffer,
  getSexFromCode: getSexFromCode,
  getNationFromCode: getNationFromCode,
  readCardIsOk,
  searchCardIsOk,
  selectCardIsOk,
  error,
  replaceErrorMsg,
  catchError
}
